package com.hxzy.controller;

import com.hxzy.pojo.User;
import com.hxzy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zl
 * @create 2020-10-29 14:32
 */
@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping(value = "/userRegister",method = RequestMethod.POST)
    public String userRegister(User user, HttpServletRequest request){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String checkCode = request.getParameter("code");
        String code = (String)request.getSession().getAttribute("KAPTCHA_SESSION_KEY");
        request.getSession().removeAttribute("KAPTCHA_SESSION_KEY");
        if (code != null && checkCode.equalsIgnoreCase(code)){
            if (!userService.existsUsername(username)){
                userService.registerUser(user);
                return "/user/regist_success";
            }else {
                //跳转到注册页面
                request.setAttribute("msg","用户名已存在");
                request.setAttribute("username",username);
                request.setAttribute("email",email);
                return "user/regist";
            }
        }else {
            System.out.println("验证码错误");
            request.setAttribute("msg","验证码错误");
            request.setAttribute("username",username);
            request.setAttribute("email",email);
            return "user/regist";
        }
    }

    @RequestMapping(value = "/loginUser",method = RequestMethod.POST)
    public String loginUser(String username, String password, HttpServletRequest request){
        User user = userService.login(username, password);
        if (user == null){
            request.setAttribute("msg","用户名或密码错误");
            request.setAttribute("username",username);
            return "user/login";
        }else {
            request.getSession().setAttribute("user",user);
            return "user/login_success";
        }
    }

    @RequestMapping("/registAjax")
    protected void registAjax(String username, HttpServletResponse resp) throws Exception {

        boolean b = userService.existsUsername(username);
        resp.getWriter().write(b ? "1":"0");
    }
}
